﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;

namespace JV.Com.Business
{
    internal static class Tools
    {
        internal static string GetValueOfElementAndCData(this XmlElement xmlElement, string nodeName)
        {
            var subElement = xmlElement.GetElementsByTagName(nodeName).FirstOrDefault() as XmlElement;
            if (subElement != null)
            {
                return subElement.GetValueOfCData();
            }
            else
            {
                return null;
            }
        }

        internal static string GetValueOfElement(this XmlElement element, string nodeName)
        {
            var subElement = element.GetElementsByTagName(nodeName).FirstOrDefault() as XmlElement;
            if (subElement != null)
            {
                return subElement.InnerText;
            }
            else
            {
                return null;
            }
        }

        internal static string GetValueOfCData(this XmlElement xmlElement)
        {
            return (string)((XmlCDataSection)xmlElement.FirstChild).NodeValue;
        }

        internal static XmlElement GetXmlRoot(string xml)
        {
            var document = new XmlDocument();
            document.LoadXml(xml);
            return document.DocumentElement;
        }

        internal static string GetConcatCData(this XmlElement element, string name)
        {
            var contentNode = element.GetElementsByTagName(name).First();
            if (contentNode is XmlElement)
            {
                var contentBuilder = new StringBuilder();
                foreach (var cdataNode in contentNode.ChildNodes)
                {
                    if (cdataNode is XmlCDataSection)
                    {
                        contentBuilder.Append(cdataNode.NodeValue);
                    }
                }
                return contentBuilder.ToString();
            }
            else return null;
        }
    }
}
